package com.itheima.reggie.Interceptor;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器验证登录
 */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断后端用户是否登录
        Long emp = (Long) request.getSession().getAttribute("emp");
        if (emp != null) {
            //已经登录
            BaseContext.setCurrentId(emp);
            return true;
        }

        //判断手机端用户是否登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            //已经登录
            BaseContext.setCurrentId(userId);
            return true;
        }


        //用户名未登录 返回前端 未登录
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(R.error("未登录")));
        return false;

    }


}
